<template>
  <div>
    <!--表格对象-->
    <DictItemManageTable
      :table="table"
      :query="query"
      :loadTableList="loadTableList"
      :changePageSize="changePageSize"
      :changePage="changePage"
      @addRow="addRow"
      @editRow="editRow"
    />
    <!--添加编辑对话框-->
    <DictItemAddOrEditDialog
      ref="dialogRef"
      :action="action"
    />
  </div>
</template>

<script lang="ts" setup>
// 导入表格组件
import DictItemManageTable from '@/views/page/system/dict/DictItemManageTable.vue';
// 导入添加编辑表单
import DictItemAddOrEditDialog from '@/views/page/system/dict/DictItemAddOrEditDialog.vue';
import {
  defineExpose, getCurrentInstance, provide, ref,
} from 'vue';
import { TableColumn } from '@/types/interface/base_interface';
import { yesOrNoDict } from '@/api/dict';
import useTableList from '@/api/common/useTableList';
import { Role } from '@/types/interface/auth_interface';
import Request from '@/api/request/request';
import { Dict } from '@/types/interface/sys_interface';

const { proxy } = getCurrentInstance();
// 表格工具必备参数
const {
  table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage,
} = useTableList(proxy.$urls.API_URL_BACKSTAGE_DICTITEM_MANAGE, true, {}, false);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);
// 定义当前的字典，用于记录字典表格所选中的当前行信息
const dict = ref<Dict>();

// 根据字典的值读取相应的字典列表项信息
const getDictItemsByDictId = async (row:Dict): Promise<void> => {
  // clearQuery();
  // 获取当前的字典信息
  dict.value = row;
  // 刷新表格
  query.value['sysDict.id'] = row.id; // 加上字典查询条件
  await loadTableList();
};
defineExpose({ // 参考vue3官方文档，需要将函数暴露出去才能被父组件调用，setup模式是不暴露的
  getDictItemsByDictId,
});
// 表单对象，决定添加编辑表单的action。
const action = ref('post');
// 打开基础对话框
const dialogRef = ref();
// 点击添加按钮
const addRow = () => {
  const form = {
    sort: 0,
    dictName: dict.value!.name,
    sysDict: {
      id: dict.value!.id,
    },
  };
  action.value = 'post';
  dialogRef.value!.openDialog(form);
};

// 编辑单行记录。
const editRow = async (row:Dict) => {
  action.value = 'put';
  // 从服务端读取该行的最新信息
  const resData:any = await new Request(`${proxy.$urls.API_URL_BACKSTAGE_DICTITEM_MANAGE}/${row.id}`).get();
  if (resData.success) {
    const form = resData.data;
    form.dictName = form.sysDict.name;
    dialogRef.value!.openDialog(JSON.parse(JSON.stringify(form)));
  }
};

</script>

<style scoped>

</style>
